﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Models;
using DAL;
using WebShopAPI.Models;//前端的处理模型类放在这里
using System.IO;
using System.Web;

namespace WebShopAPI.Controllers
{
    public class goodsController : ApiController
    {
        sp_goodsServcie goodServcie = new sp_goodsServcie();// 商品表操作类

        sp_goods_attrService sp_goods_attService=new sp_goods_attrService();//商品参数表操作类

        sp_goods_picsService sp_Goods_PicsServcie = new sp_goods_picsService(); //商品图片操作类

        #region 1.8.1. 商品列表数据  //注意这些方法也可以写在数据服务层
        public ResponData Get(string query, int pagenum = 1, int pagesize = 10)
        {
            //全部数据
            List<sp_goods> goodsList = goodServcie.GetAll();
            //条件查询
            if (!string.IsNullOrEmpty(query))
            {
                goodsList = goodsList.Where(p => p.goods_name.Contains(query)).ToList();
            }
            int total = goodsList.Count();//总记录数

            int n = (pagenum - 1) * pagesize;

            var rlist=goodsList.OrderByDescending(p=>p.goods_id)
                .Skip(n).Take( pagesize );
            ////////////响应数据处理///////////////////
            ResponData rd = new ResponData();
            rd.data = new
            {
                total = total,
                pagenum = pagenum,
                goods = rlist.Select(
                    p => new 
                {
                    p.goods_id,
                    p.goods_name,  
                    p.goods_price,
                    p.goods_number,
                    p.goods_weight,
                    p.goods_state,
                    p.add_time,
                    p.upd_time,
                    p.hot_mumber,
                    p.is_promote
                })
            };
            rd.meta.msg = "获取成功";
            rd.meta.status = 200;
            return rd;
        }
        #endregion

        #region 1.8.2. 添加商品 ,该操作将操作多个表，注意需要创建一个请求对象类
        //因为它不能一个单表的简单操作
        public ResponData Post(AddGoodRequest addrequest)
        {
            //类别值分隔成数组
            string[] carts = addrequest.goods_cat.Trim().Split(',');
            //1 增加商品表信息，真正实现应该写在业务层或访问层，并需要使用事务
            // https://www.cnblogs.com/wyy1234/p/9645796.html
            sp_goods sp_goods = new sp_goods();
            sp_goods.goods_name = addrequest.goods_name;
            sp_goods.goods_price = addrequest.goods_price;
            sp_goods.goods_number=addrequest.goods_number;
            sp_goods.goods_weight =(short)addrequest.goods_weight;
            sp_goods.cat_id = short.Parse(carts[2]); //数据库是短整型
            sp_goods.goods_introduce = addrequest.goods_introduce;
            //大图小图路径处理
            if (addrequest.pics.Count > 0)
            {
                string guidId = Guid.NewGuid().ToString();//用Guid保存唯一
                string ExtName = Path.GetExtension(addrequest.pics[0].pic.ToString());
                string g_max_img = "upload/goodspics/big_" + guidId +""+ExtName;
                string g_mid_img = "upload/goodspics/mid_" + guidId + "" + ExtName;
                string g_small_img = "upload/goodspics/sma_" + guidId + "" + ExtName;
                //调用图片处理的方法处理出图片
                //HttpContext为请求上下文，用来获取当前请求对象 才可以在web api/mvc中使用web 系统对象
                //大图转换 注意所有的尺寸根所前台显示定义，可以把值配置在参数中
                ImageHelper.MakeThumbnail(
                     HttpContext.Current.Server.MapPath("~/"
                    + addrequest.pics[0].pic.ToString()), //源路径 需要转成物理路径

                   HttpContext.Current.Server.MapPath("~/"
                    + g_max_img),

                       300, 400, "W"

                    );
                //中图转换
                ImageHelper.MakeThumbnail(
                   HttpContext.Current.Server.MapPath("~/"
                  + addrequest.pics[0].pic.ToString()), //源路径 需要转成物理路径

                 HttpContext.Current.Server.MapPath("~/"
                  + g_mid_img),

                     200, 300, "W"

                  );
                //小图转换
                ImageHelper.MakeThumbnail(
                   HttpContext.Current.Server.MapPath("~/"
                  + addrequest.pics[0].pic.ToString()), //源路径 需要转成物理路径

                 HttpContext.Current.Server.MapPath("~/"
                  + g_small_img),

                     150, 200, "W"

                  );
                sp_goods.goods_big_logo = g_max_img;
                sp_goods.goods_small_logo = g_small_img;
            }
            sp_goods.is_del = 1;//没有删除用1
            sp_goods.add_time = (int)((DateTime.Now - new DateTime(2000, 1, 1)).Ticks); //计算当前到一个指定的日期
            sp_goods.upd_time = (int)((DateTime.Now - new DateTime(2000, 1, 1)).Ticks);
            sp_goods.cat_one_id= short.Parse(carts[0]);
            sp_goods.cat_two_id = short.Parse(carts[1]);
            sp_goods.cat_three_id = short.Parse(carts[2]);
            sp_goods.hot_mumber = 0;//热销数
            sp_goods.is_promote = 0;//不是热销 1,热销
            sp_goods.goods_state = 1;//上架状态，可以销售
            //调用增加商品方法
            goodServcie.Add(sp_goods);
            //增加完成再增加商品的图片及商品的参数，以便后面完成 SKU 了解一下SKU
            //图片表保存数据
            foreach (var obj in addrequest.pics)
            {
                sp_goods_pics picobj = new sp_goods_pics();
                picobj.goods_id = sp_goods.goods_id;//获取到商品的id号
                /////////图片处理///////////////
                string guidId = Guid.NewGuid().ToString();//用Guid保存唯一
                string ExtName = Path.GetExtension(obj.pic);
                string g_max_img = "upload/goodspics/big_" + guidId + "" + ExtName;
                string g_mid_img = "upload/goodspics/mid_" + guidId + "" + ExtName;
                string g_small_img = "upload/goodspics/sma_" + guidId + "" + ExtName;
                //调用图片处理的方法处理出图片
                //HttpContext为请求上下文，用来获取当前请求对象 才可以在web api/mvc中使用web 系统对象
                //大图转换 注意所有的尺寸根所前台显示定义，可以把值配置在参数中
                ImageHelper.MakeThumbnail(
                     HttpContext.Current.Server.MapPath("~/"
                    + obj.pic.ToString()), //源路径 需要转成物理路径

                   HttpContext.Current.Server.MapPath("~/"
                    + g_max_img),

                       300, 400, "W"

                    );
                //中图转换
                ImageHelper.MakeThumbnail(
                   HttpContext.Current.Server.MapPath("~/"
                  + obj.pic.ToString()), //源路径 需要转成物理路径

                 HttpContext.Current.Server.MapPath("~/"
                  + g_mid_img),

                     200, 300, "W"

                  );
                //小图转换
                ImageHelper.MakeThumbnail(
                   HttpContext.Current.Server.MapPath("~/"
                  + obj.pic.ToString()), //源路径 需要转成物理路径

                 HttpContext.Current.Server.MapPath("~/"
                  + g_small_img),

                     150, 200, "W"

                  );
                ///////////////////////////////
                picobj.pics_big = g_max_img;
                picobj.pics_mid = g_mid_img;
                picobj.pics_sma = g_small_img;
                //保存图片
                sp_Goods_PicsServcie.Add(picobj);
            }
            //循环参数
            foreach (var attobj in addrequest.attrs)
            {
                sp_goods_attr addattobj = new sp_goods_attr();//要增加到参数表的参数对象
                addattobj.goods_id= sp_goods.goods_id;//商品id
                addattobj.attr_id = attobj.attr_id;
                addattobj.attr_value= attobj.attr_value;
                addattobj.add_price = 0;
                //调用增加,批量
                sp_goods_attService.Add(addattobj);

            }
             //////////响应数据部分////////////////////
            ResponData rd = new ResponData();
            //响应数据暂末处理，没有看到在哪用,估计是为了让方便前端检查
            rd.meta.status = 200;
            rd.meta.msg = "创建商品成功";
            return rd;
        }
        #endregion

        #region 1.8.3. 根据 ID 查询商品
        #endregion


        #region 1.8.4. 编辑提交商品
        #endregion


        #region 1.8.5. 删除商品
        #endregion

    }

    //根据功能需要，接受前端传过来的复杂数据，定义一个类
    /*
        goods_name: '',
        goods_cat: '', // 类别用,分开
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_introduce: '',
        pics: [], // 对象数组,用来保存上传的图片
        attrs: [] // 对象数组,设置的对应参数的值数组
     */
    public class AddGoodRequest
    { 
        //商品名
        public string goods_name { get; set; }
        //传过来已由数组转成字符串
        public string goods_cat { get; set; }
        //价格
        public decimal goods_price { get; set; }
        //数量
        public int goods_number { get; set; }
        //重量
        public int goods_weight { get; set; }

        //描述
        public string goods_introduce { get; set; }
        //接收上传的对象数组
        public List<PicPath> pics { get; set; }

        //接收数组参数
        public List<AttrInto> attrs { get; set; }
    }
    /// <summary>
    /// 图片是对象数组，后台用集合接收
    /// </summary>
    public class PicPath
    { 
        public string pic { get; set; }
    }
    /// <summary>
    /// 参数传过来也是对象数组，先定义一个类对应
    /// </summary>
    public class AttrInto 
    {
        public int attr_id { get; set; }
        public string attr_value { get; set; }

    }

}
